<template>
  <div class="etnor-api-doc">
    <!-- 顶部轮播图 -->
    <el-carousel :interval="4000" type="card" height="400px" class="banner-carousel">
      <el-carousel-item v-for="item in carouselItems" :key="item.id">
        <div class="carousel-content" :style="{ backgroundImage: `url(${item.image})` }">
          <div class="carousel-overlay">
            <h2>{{ item.title }}</h2>
            <p>{{ item.description }}</p>
            <el-button type="primary" class="carousel-btn" @click="handleCarouselAction(item)">
              {{ item.buttonText }}
            </el-button>
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>

    <!-- 顶部横幅 -->
    <div class="banner">
      <div class="banner-content">
        <h1>{{ messages[currentLanguage].title }}</h1>
        <p class="subtitle">{{ messages[currentLanguage].subtitle }}</p>
      </div>
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          :placeholder="currentLanguage === 'zh' ? '搜索API文档...' : 'Search API docs...'"
          class="search-input"
        >
          <template #prefix>
            <i class="el-icon-search"></i>
          </template>
        </el-input>
        <el-select 
          v-model="categoryFilter" 
          class="category-filter"
          :placeholder="currentLanguage === 'zh' ? '选择分类' : 'Select Category'"
        >
          <el-option
            v-for="category in categories"
            :key="category.value"
            :label="category.label"
            :value="category.value"
          />
        </el-select>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-card class="stat-card" shadow="hover">
        <i class="el-icon-document"></i>
        <div class="stat-info">
          <span class="stat-number">{{ docs.length }}</span>
          <span class="stat-label">{{ messages[currentLanguage].totalDocs }}</span>
        </div>
      </el-card>
      <el-card class="stat-card" shadow="hover">
        <i class="el-icon-view"></i>
        <div class="stat-info">
          <span class="stat-number">{{ totalViews }}</span>
          <span class="stat-label">{{ messages[currentLanguage].totalViews }}</span>
        </div>
      </el-card>
    </div>

    <!-- 文档列表 -->
    <div class="documentation-grid">
      <el-card 
        v-for="doc in filteredDocs" 
        :key="doc.id" 
        class="doc-card"
        shadow="hover"
      >
        <div class="doc-card-header">
          <el-tag size="small" :type="getTagType(doc.category)">
            {{ doc.category }}
          </el-tag>
          <span class="doc-date">{{ formatDate(doc.updateTime) }}</span>
        </div>
        <h3 class="doc-title">{{ doc.title }}</h3>
        <p class="doc-description">{{ doc.description }}</p>
        <div class="doc-footer">
          <el-button 
            type="primary" 
            @click="viewArticle(doc)"
            icon="el-icon-document"
          >
            {{ currentLanguage === 'zh' ? '查看文档' : 'View Document' }}
          </el-button>
          <div class="doc-stats">
            <span class="stat">
              <i class="el-icon-view"></i>
              {{ doc.views || 0 }}
            </span>
            <span class="stat">
              <i class="el-icon-star-off"></i>
              {{ doc.likes || 0 }}
            </span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <el-empty
      v-if="filteredDocs.length === 0"
      :description="currentLanguage === 'zh' ? '暂无相关文档' : 'No documents found'"
    />
  </div>
</template>

<script>
import { messages } from "@/languages/etnorApiDoc-language.js";
import axios from 'axios';

export default {
  name: "EtnorAPIAdminDoc",
  props: {
    currentLanguage: {
      type: String,
      default: "zh",
    },
  },
  data() {
    return {
      searchQuery: "",
      messages,
      docs: [],
      categoryFilter: '',
      totalViews: 0,
      categories: [
        { value: '', label: this.currentLanguage === 'zh' ? '全部' : 'All' },
        { value: 'rest', label: 'REST API' },
        { value: 'websocket', label: 'WebSocket' },
        { value: 'sdk', label: 'SDK' }
      ],
      carouselItems: [
        {
          id: 1,
          title: this.currentLanguage === 'zh' ? 'REST API 快速入门' : 'REST API Quick Start',
          description: this.currentLanguage === 'zh' 
            ? '探索我们强大的REST API，轻松集成您的应用' 
            : 'Explore our powerful REST API for seamless integration',
          image: 'https://images.unsplash.com/photo-1451187580459-43490279c0fa?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80',
          buttonText: this.currentLanguage === 'zh' ? '立即开始' : 'Get Started',
          action: 'rest'
        },
        {
          id: 2,
          title: this.currentLanguage === 'zh' ? 'WebSocket 实时通信' : 'WebSocket Real-time Communication',
          description: this.currentLanguage === 'zh'
            ? '体验毫秒级的实时数据传输能力'
            : 'Experience millisecond-level real-time data transmission',
          image: 'https://images.unsplash.com/photo-1558494949-ef010cbdcc31?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80',
          buttonText: this.currentLanguage === 'zh' ? '了解更多' : 'Learn More',
          action: 'websocket'
        },
        {
          id: 3,
          title: this.currentLanguage === 'zh' ? 'SDK 开发工具包' : 'SDK Development Kit',
          description: this.currentLanguage === 'zh'
            ? '使用我们的SDK，快速构建功能强大的应用'
            : 'Build powerful applications quickly with our SDK',
          image: 'https://images.unsplash.com/photo-1517134191118-9d595e4c8c2b?ixlib=rb-4.0.3&auto=format&fit=crop&w=1920&q=80',
          buttonText: this.currentLanguage === 'zh' ? '获取SDK' : 'Get SDK',
          action: 'sdk'
        }
      ]
    };
  },
  computed: {
    filteredDocs() {
      return this.docs.filter(doc => {
        const matchesSearch = doc.title.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
          doc.description.toLowerCase().includes(this.searchQuery.toLowerCase());
        const matchesCategory = !this.categoryFilter || doc.category === this.categoryFilter;
        return matchesSearch && matchesCategory;
      });
    }
  },
  methods: {
    getTagType(category) {
      const types = {
        'rest': 'success',
        'websocket': 'warning',
        'sdk': 'info'
      };
      return types[category] || 'primary';
    },
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      const now = new Date();
      const diff = now - d;
      const days = Math.floor(diff / (1000 * 60 * 60 * 24));
      
      if (days === 0) {
        return this.currentLanguage === 'zh' ? '今天' : 'Today';
      } else if (days === 1) {
        return this.currentLanguage === 'zh' ? '昨天' : 'Yesterday';
      } else if (days < 30) {
        return this.currentLanguage === 'zh' 
          ? `${days}天前` 
          : `${days} days ago`;
      } else {
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    },
    async viewArticle(doc) {
      try {
        await this.incrementViews(doc.id);
        this.$router.push('/article/' + doc.articleId);
      } catch (error) {
        console.error('Error viewing article:', error);
      }
    },
    async fetchDocs() {
      try {
        const token = localStorage.getItem('token');
        const config = {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json;charset=UTF-8'
          }
        };
        const response = await axios.get('/api/system/doc/article/api-docs', config);
        if (response.data.code === 200) {
          this.docs = response.data.data;
          this.totalViews = this.docs.reduce((sum, doc) => sum + (doc.views || 0), 0);
        }
      } catch (error) {
        console.error('请求错误:', error);
        this.$message.error(this.currentLanguage === 'zh' ? '获取文档失败' : 'Failed to fetch documents');
      }
    },
    async incrementViews(docId) {
      // 实现查看次数增加的API调用
    },
    handleCarouselAction(item) {
      const routes = {
        'rest': '/docs/rest-api',
        'websocket': '/docs/websocket',
        'sdk': '/docs/sdk'
      };
      
      if (routes[item.action]) {
        this.$router.push(routes[item.action]);
      }
    }
  },
  mounted() {
    this.fetchDocs();
  }
};
</script>

<style scoped>
.etnor-api-doc {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.banner {
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  padding: 40px 20px;
  border-radius: 12px;
  color: white;
  margin-bottom: 30px;
}

.banner-content {
  text-align: center;
  margin-bottom: 20px;
}

.banner h1 {
  font-size: 2.5em;
  margin: 0;
  font-weight: 600;
}

.subtitle {
  font-size: 1.2em;
  opacity: 0.9;
  margin-top: 10px;
}

.search-section {
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  gap: 15px;
}

.search-input {
  flex: 1;
}

.category-filter {
  width: 150px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-card i {
  font-size: 2em;
  margin-right: 15px;
  color: #1890ff;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-number {
  font-size: 1.5em;
  font-weight: bold;
  color: #1890ff;
}

.stat-label {
  color: #666;
}

.documentation-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.doc-card {
  transition: transform 0.2s;
}

.doc-card:hover {
  transform: translateY(-5px);
}

.doc-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.doc-date {
  font-size: 0.9em;
  color: #999;
}

.doc-title {
  margin: 10px 0;
  font-size: 1.2em;
  color: #2c3e50;
}

.doc-description {
  color: #666;
  margin-bottom: 20px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.doc-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.doc-stats {
  display: flex;
  gap: 15px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
}

.stat i {
  font-size: 1.1em;
}

@media (max-width: 768px) {
  .search-section {
    flex-direction: column;
  }
  
  .category-filter {
    width: 100%;
  }
  
  .documentation-grid {
    grid-template-columns: 1fr;
  }
}

.banner-carousel {
  margin-bottom: 30px;
}

.carousel-content {
  height: 100%;
  background-size: cover;
  background-position: center;
  border-radius: 12px;
  overflow: hidden;
  position: relative;
}

.carousel-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    rgba(0, 0, 0, 0.1),
    rgba(0, 0, 0, 0.7)
  );
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px;
  text-align: center;
  color: white;
}

.carousel-overlay h2 {
  font-size: 2.5em;
  margin-bottom: 15px;
  font-weight: 600;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.carousel-overlay p {
  font-size: 1.2em;
  margin-bottom: 25px;
  max-width: 600px;
  line-height: 1.6;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
}

.carousel-btn {
  padding: 12px 30px;
  font-size: 1.1em;
  border-radius: 25px;
  transition: transform 0.2s;
}

.carousel-btn:hover {
  transform: scale(1.05);
}

@media (max-width: 768px) {
  .banner-carousel {
    margin-bottom: 20px;
  }

  .carousel-overlay h2 {
    font-size: 1.8em;
  }

  .carousel-overlay p {
    font-size: 1em;
  }

  .carousel-btn {
    padding: 8px 20px;
    font-size: 1em;
  }
}
</style>
  